from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializers import AreaSerializer, SubsAreaSerializer

# class ProvienceAPIView(APIView):
#
#     def get(self,request):
#
#         #1.获取所有的省的数据    [Area,Area,Area]
#         areas = Area.objects.filter(parent=None)
#         #2. 将对象列表转换为字典列表
#         serializer = AreaSerializer(areas,many=True)
#         #3. 返回相应
#         return Response(serializer.data)
#
# #市
# # select * from tb_areas where parent_id=130000;
# #区县
# # select * from tb_areas where parent_id=130600;
#
# # areas/infos/pk/
# class CityAPIView(APIView):
#
#     def get(self,request,pk):
#
#         #1. 获取指定数据  [Area,Area,Area]
#         areas = Area.objects.filter(parent=pk)
#         #2.将对象列表转换为 字典列表
#         serialiaer = AreaSerializer(areas,many=True)
#         #3.返回相应
#         return Response(serialiaer.data)

class AreaModelViewSet(ReadOnlyModelViewSet,CacheResponseMixin):

    # queryset = Area.objects.filter(parent=None) # 省
    # queryset = Area.objects.all() #市，区县
    pagination_class = None

    def get_queryset(self):

        # action   list,retrieve,update,delete,create

        # 我们的list 就是获取省的数据              areas/infos/
        # retrieve 就是获取 市，区县信息          areas/infos/pk/
        if self.action == 'list':
            # 省的信息
            return Area.objects.filter(parent=None)
        else:
            # 区县信息
            return Area.objects.all()

    # serializer_class = AreaSerializer
    # serializer_class = AreaSerializer   #省
    # serializer_class = SubsAreaSerializer   #市

    def get_serializer_class(self):

        if self.action == 'list':
            return AreaSerializer
        else:
            return SubsAreaSerializer